package cz.vutbr.fit.xzemko01.tfmcbs.validation.validators;

import java.util.Map;

import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.DiagnosticChain;

import cz.vutbr.fit.xzemko01.tfmcbs.model.Dependency;
import cz.vutbr.fit.xzemko01.tfmcbs.model.Entity;
import cz.vutbr.fit.xzemko01.tfmcbs.model.Relationship;
import cz.vutbr.fit.xzemko01.tfmcbs.validation.utils.DiagnosticBuilder;

public final class DependencyValidator implements Validator<Dependency> {

	private static DependencyValidator dependencyValidator;
	
	private Validator<Relationship> relationshipValidator;
	
	private DependencyValidator() {
		relationshipValidator = RelationshipValidator.getInstance();
	}
	
	public static Validator<Dependency> getInstance() {
		if(dependencyValidator == null) {
			dependencyValidator = new DependencyValidator();
		}
		return dependencyValidator;
	}
	
	@Override
	public boolean validate(Dependency dependency, DiagnosticChain diagnostics, Map<Object, Object> context) {
		boolean result = relationshipValidator.validate(dependency, diagnostics, context);
		result &= validateStereotypeNotEmpty(dependency, diagnostics, context);
		result &= validateDependencyEnds(dependency, diagnostics, context);
		return result;
	}
	
	private boolean validateStereotypeNotEmpty(Dependency dependency, DiagnosticChain diagnostics, Map<Object, Object> context) {
		String stereoType = dependency.getStereotype();
		boolean result = true;

		if (stereoType == null || stereoType.trim().isEmpty()) {
			String errorMessage = "Dependency \"" + dependency.getName() + "\" stereotype is empty.";
			Diagnostic diagnostic = 
					new DiagnosticBuilder(dependency).setMessage(errorMessage).build();
			diagnostics.add(diagnostic);
			result = false;
		}
		return result;
	}
	
	private boolean validateDependencyEnds(Dependency dependency, DiagnosticChain diagnostics, Map<Object, Object> context) {
		Entity dependsFrom = dependency.getFrom();
		Entity dependsTo = dependency.getTo();
		
		if(dependsFrom == null) {
			Diagnostic diagnostic = new DiagnosticBuilder(dependency)
						.setMessage("Dependency \"" + dependency.getName() 
								+ "\" has not set dependency \"from\" entity.").build();
			diagnostics.add(diagnostic);
			return false;
		} else if(dependsTo == null) {
			Diagnostic diagnostic = new DiagnosticBuilder(dependency)
						.setMessage("Dependency \"" + dependency.getName() 
								+ "\" has not set dependency \"to\" entity.").build();
			diagnostics.add(diagnostic);
			return false;
		}
		return true;		
	}
}
